package com.example.javaproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javaproject.common.R;
import com.example.javaproject.entity.User;
import com.example.javaproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") Integer page,
                  @RequestParam(defaultValue = "10") Integer size,
                  @RequestParam(required = false) String username,
                  @RequestParam(required = false) Integer role) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("is_deleted", 0);
        if (username != null && !username.isEmpty()) query.like("username", username);
        if (role != null) query.eq("role", role);
        Page<User> pageObj = userService.page(new Page<>(page, size), query);
        return R.ok(pageObj);
    }

    @PutMapping("/update")
    public R update(@RequestBody User user) {
        // 获取原始用户信息
        User originalUser = userService.getById(user.getId());
        if (originalUser == null) {
            return R.error("用户不存在");
        }

        user.setUpdateTime(java.time.LocalDateTime.now());
        
        // 如果角色发生变化，使用updateUserRole方法
        if (!originalUser.getRole().equals(user.getRole())) {
            boolean success = userService.updateUserRole(user);
            return success ? R.ok(null) : R.error("修改失败");
        } else {
            // 如果角色没有变化，使用普通的更新方法
            boolean success = userService.updateById(user);
            return success ? R.ok(null) : R.error("修改失败");
        }
    }
} 